//
//  NewsListTableViewController.m
//  QQ_Youngsher
//
//  Created by Maxwell on 16/1/20.
//  Copyright © 2016年 LLLTeam. All rights reserved.
//

#import "NewsListTableViewController.h"
#import <AFNetworking.h>
#import <AFNetworkReachabilityManager.h>
#import <UIImageView+WebCache.h>
#import <MJRefresh.h>
#import "Friend.h"
#import "DetailTableViewCell.h"

#define SCREEN_W [[UIScreen mainScreen] bounds].size.width
#define SCREEN_H [[UIScreen mainScreen] bounds].size.height

static NSString *const dataURL = @"http://f.wallstcn.com/news.json";

@interface NewsListTableViewController ()

@property (nonatomic ,strong)NSMutableArray *dataSourceArray;//数据源数组

@end

@implementation NewsListTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    _dataSourceArray = [[NSMutableArray alloc] init];
    
    UIButton *searchBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    searchBtn.frame = CGRectMake(5, 5, SCREEN_W - 10, 25);
    searchBtn.backgroundColor = [UIColor colorWithRed:0.8627 green:0.8627 blue:0.8627 alpha:1.0];
    [searchBtn setTitle:@"搜索" forState:UIControlStateNormal];
    [searchBtn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
    searchBtn.titleLabel.font = [UIFont systemFontOfSize:13];
    searchBtn.tag = 0;
    [searchBtn addTarget:self action:@selector(clickHeadViewBtn:) forControlEvents:UIControlEventTouchUpInside];
    searchBtn.layer.cornerRadius = 4.0;
    searchBtn.layer.masksToBounds = YES;
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_W, 35)];
    [view addSubview:searchBtn];
    self.tableView.tableHeaderView = view;
    
    [self requestNewsData];
    //    下拉刷新
    __weak typeof(self) weakself =  self;
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
//        __strong typeof(weakself) strongself = weakself;
//        if (strongself) {
//            [self requestNewsData];
//        }
        if (weakself){
            [self requestNewsData];
        }
    }];
    
    //设置时间接收数据
    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:10 target:self selector:@selector(reciveNews) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
    
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}

- (void)reciveNews{
    NSInteger index = arc4random()%_dataSourceArray.count;
    [_dataSourceArray removeAllObjects];
    NSString *filePath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];
    NSString *dataPath = [filePath stringByAppendingPathComponent:@"dataSourceArray.data"];
    _dataSourceArray =[NSKeyedUnarchiver unarchiveObjectWithFile:dataPath];
    Friend *friend = _dataSourceArray[index];
    [friend.newsListArray addObject:friend.intro];
    friend.intro = @"这是接收到的一条新数据";
    NSDate *date = [NSDate date];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"HH:mm"];
    friend.newsDate = [dateFormatter stringFromDate:date];
    NSInteger offNews = [friend.offNews intValue];
    offNews ++;
    friend.offNews = [NSString stringWithFormat:@"%ld",(long)offNews];
    [_dataSourceArray insertObject:_dataSourceArray[index] atIndex:0];
    [_dataSourceArray removeObjectAtIndex:index + 1];
    [self.tableView reloadData];
    //数据归档
    [NSKeyedArchiver archiveRootObject:_dataSourceArray toFile:dataPath];
    
}
- (void)clickHeadViewBtn:(UIButton *)btn{
    NSLog(@" %d | %s | %@",__LINE__,__FUNCTION__,btn);
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)requestNewsData{
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager GET:dataURL parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        NSLog(@" %d | %s | %@",__LINE__,__FUNCTION__,downloadProgress);
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSMutableArray *arr = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        NSLog(@"数据请求成功");
        
        //数据请求成功
        [_dataSourceArray removeAllObjects];
        for (NSDictionary *dic in arr) {
            NSMutableArray *authorsArr = dic[@"authors"];
            for (NSDictionary *dict in authorsArr) {
                Friend *friend = [[Friend alloc] init];
                [friend setValuesForKeysWithDictionary:dict];
                [_dataSourceArray addObject:friend];
            }
        }
        
        //存储数据
        NSString *filePath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];
        NSString *dataPath = [filePath stringByAppendingPathComponent:@"dataSourceArray.data"];
        //归档
        [NSKeyedArchiver archiveRootObject:_dataSourceArray toFile:dataPath];
        
        [self.tableView reloadData];
        [self.tableView.mj_header endRefreshing];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"数据请求失败");
        [self.tableView.mj_header endRefreshing];
    }];
    
}


#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _dataSourceArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 70;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *identifier = @"DetailTableViewCell";
    DetailTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[[NSBundle mainBundle] loadNibNamed:identifier owner:self options:nil] lastObject];
        Friend *friend = _dataSourceArray[indexPath.row];
        cell.nameLabel.text = friend.nickname;
        cell.zoneLabel.text = friend.intro;
        [cell.headImageView sd_setImageWithURL:[NSURL URLWithString:friend.avatar] placeholderImage:[UIImage imageNamed:@"contact_y"]];
        if ([friend.offNews isEqualToString:@"0"]) {
            cell.newsLabel.hidden = YES;
        }
        cell.newsLabel.text = friend.offNews;
        if ([friend.offNews intValue] > 99) {
            cell.newsLabel.text = @"99+";
        }
        cell.timeLabel.text = friend.newsDate;
        if ([friend.newsDate isEqualToString:@"0"]) {
            cell.timeLabel.hidden = YES;
        }
    }
    return cell;
    
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    Friend *friend =  _dataSourceArray[indexPath.row];
    friend.offNews = @"0";
    NSString *filePath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];
    NSString *dataPath = [filePath stringByAppendingPathComponent:@"dataSourceArray.data"];
    //归档
    [NSKeyedArchiver archiveRootObject:_dataSourceArray toFile:dataPath];
    [self.tableView reloadData];
    
    
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
